package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author shenkunlin
 * @date 2025-01-09
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;


    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /****
     * 根据入住ID查询详情信息
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //1、查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        //2、查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()));

        //3、查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());

        //4、家属信息
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(checkIn.getRemark(),ElderFamilyVo.class);

        //5、查询合同信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId,elder.getId()));

        //6、VO转换   家属信息缺失
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setBedNumber(elder.getBedNumber());

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        return checkInDetailVo;
    }

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }




    /****
     * 1）判断老人是否已经入住，如果已经入住，则直接结束程序
     * 2）老人已经入住，需要更新床位状态
     * 3）新增老人信息或者更新老人信息
     * 4）新增签约信息
     * 5）新增入住信息
     * 6）新增入住配置信息
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //1）判断老人是否已经入住，如果已经入住，则直接结束程序
        Elder elder = elderMapper.selectOne(
                Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1)
        );
        if(!ObjectUtils.isEmpty(elder)){
            throw new BaseException("老人已入住！");
        }

        //2）老人未入住，需要更新床位状态，改成已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3）新增老人信息或者更新老人信息
        elder = insertOrUpdate(bed,dto.getCheckInElderDto());

        //4）新增签约信息
        String contractNumber = "HT"+ CodeGenerator.generateContractNumber();
        insertContract(contractNumber,elder,dto.getCheckInConfigDto(),dto.getCheckInContractDto());

        //5）新增入住信息
        CheckIn checkIn = insertCheckIn(elder,dto.getCheckInConfigDto(),dto.getElderFamilyDtoList());

        //6）新增入住配置信息
        insertCheckInConfig(checkIn.getId(),dto.getCheckInConfigDto());
    }



    /***
     * 新增入住配置信息
     */
    public void insertCheckInConfig(Long checkInId, CheckInConfigDto checkInConfigDto){
        //1、创建CheckInConfig  拷贝属性值
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);

        //2、设置checkInId
        checkInConfig.setCheckInId(checkInId);

        //3、新增
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    /****
     * 新增入住信息
     */
    public CheckIn insertCheckIn(Elder elder,CheckInConfigDto  checkInConfigDto,List<ElderFamilyDto> elderFamilyDtoList){
        //1、创建实体类
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInConfigDto,checkIn);

        //2、完善其他信息
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());

        //3、家属添加
        String familyJson = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(familyJson);

        //4、执行新增
        checkInMapper.insertCheckIn(checkIn);
        return checkIn;
    }


    /****
     * 新增签约信息
     */
    public void insertContract(String contractNumber,Elder elder, CheckInConfigDto checkInConfigDto, CheckInContractDto checkInContractDto){
        //1、创建签约对象
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setContractNumber(contractNumber);

        //2、完善信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = checkInConfigDto.getStartDate();
        LocalDateTime endDate = checkInConfigDto.getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        int status = startDate.isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);

        //3、新增操作
        contractMapper.insert(contract);
    }

    /***
     * 新增老人信息或者更新老人信息
     *  checkInElderDto、Bed
     */
    public Elder insertOrUpdate(Bed bed, CheckInElderDto dto){
        //1、根据身份号判断老人信息是否存在
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCardNo()));

        //2、如果存在，则更新老人信息----【状态更新成启用】
        if(!ObjectUtils.isEmpty(elder)){
            BeanUtils.copyProperties(dto,elder);
            elder.setStatus(1);
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
            return elder;
        }
        elder = new Elder();
        //3、如果不存在，则新增老人信息----【状态启用】
        BeanUtils.copyProperties(dto,elder);
        elder.setStatus(1);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elderMapper.insert(elder);
        return elder;
    }



}
